package club.dingzm.ddxcdemo.model.demo.controller;

import club.dingzm.ddxcdemo.common.entity.Result;
import club.dingzm.ddxcdemo.common.utils.MD5Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName demoController
 * @Description TODO http文件分片上传接口
 * @Author Dingzm
 * @Date 2021/8/14 12:49
 * @Version 1.0
 */
@RestController
@RequestMapping("demo")
public class demoController {


    @Value("${staticFilePath}")
    private String upLoadPath;


    @PostMapping(value = "/uploadFileBytes")
    public Result<?> uploadFileBytes(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        int start = Integer.valueOf(request.getParameter("start"));
        int end = Integer.valueOf(request.getParameter("end"));
        String filename = request.getParameter("fileName");
        String md5 = request.getParameter("md5");
        String cacheId = request.getParameter("cacheId");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        System.out.println("开始进入文件分片上传：当前分片："+start+"   文件总分片:"+end);
        String fileTempName = start+"-"+filename;
        String ctxPath = upLoadPath + File.separator+"app"+ File.separator+cacheId+File.separator;

        File file1=new File(ctxPath+fileTempName+".temp");
        File fileTemp = new File( ctxPath );
        if (!fileTemp.exists()) {
            fileTemp.mkdirs();// 创建文件根目录
        }
        try {
            //保存当前文件
            FileCopyUtils.copy(file.getBytes(), file1);

            // 如果 是最后一个分片文件 那么进行 临时文件合并
            if (start == end){
                File file2 = new File(ctxPath + filename + ".temp");
                if ( !file2.exists()){
                    file2.createNewFile();
                }
                RandomAccessFile resFile=new RandomAccessFile(ctxPath+filename+".temp", "rw");
                FileInputStream in = null;
                for (int i = 0; i <= end ; i++) {

                    File temp = new File(ctxPath + i + "-" + filename + ".temp");
                    if (temp.exists()){
                        in = new FileInputStream(temp);
                        int len;
                        byte[] bytes = new byte[1024];
                        while ((len = in.read(bytes)) >= 0 ) {
                            resFile.write(bytes,0,len);
                        }
                        if (in != null){
                            in.close();
                        }
                    }
                    temp.delete();

                }
                if (in != null){
                    in.close();
                }
                resFile.close();
                file2.renameTo(new File(ctxPath + filename));
                String fileMD5String = MD5Util.getFileMD5String(ctxPath + filename );
                if ( !fileMD5String.equals(md5)){
                    return result.error500("文件MD5校验失败！");
                }

            }

            return Result.ok();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.error500("服务器异常");
        } catch (IOException e) {
            e.printStackTrace();
            result.error500("服务器异常");
        }
        return result;

    }

}
